package server;

import game.SuperGame;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import player.Player;

public class ThreadListentPlayer extends Thread {

	final Socket clientSocket;
	BufferedReader in = null;
	SuperGame game = null;

	// thread allowing to get all the msg sent to referee
	ThreadListentPlayer(Socket clientSocket, SuperGame game) {
		this.clientSocket = clientSocket;
		this.game = game;
	}

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
		
				// if message is not empty
				if (!inputLine.equals("")) {
					System.out.println("dans le thread on recoit"+inputLine);
					// find for the player who sent the message
					for (Player p : game.getListPlayer()) {
						// if player's socket and message sender's socket are equal
						if ((p.getTmpSocket().equals(clientSocket))) {
							System.out.println("c'est " + p.getPseudo() + "qui envoi le message");
							// set message of this player
							p.setCurrentMsg(inputLine);
							inputLine = "";
							// launch action of the game

							game.play();
						}
					}
				}

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				in.close();
				clientSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
